package com.ambimmort.shj.service;

import cn.net.greenet.db.bean.Hfdb;
import net.sf.json.JSONArray;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hedingwei on 7/29/15.
 */
@Service
public class GenaralFileService {

    @Autowired
    private SessionFactory hibernateSessionFactory;


    public void addBlackDomain(String content) throws Throwable{
        JSONArray arr = JSONArray.fromObject(content);
        Session session = hibernateSessionFactory.openSession();
        session.clear();
        Transaction tx = session.beginTransaction();
        String hql = "from Hfdb";
        List hfdbs = session.createQuery(hql).list();
        Map<String, Integer> map = new HashMap<String, Integer>();
        if (!hfdbs.isEmpty()) {
            for (int i = 0; i < hfdbs.size(); i++) {
                Hfdb hd = (Hfdb) hfdbs.get(i);
                map.put(hd.getFilter(), hd.getId());
            }
        }
        Hfdb hfdb = null;
        try {
            for (int i = 0; i < arr.size(); i++) {
                String url = arr.get(i).toString();
                if (!map.containsKey(url)) {
                    hfdb = new Hfdb(url);
                    session.save(hfdb);
                    int id = map.size() + 1;
                    map.put(url, id);
                }
            }
            tx.commit();

        } catch (Exception e) {
            tx.rollback();

        } finally {
            session.close();
        }
    }
}
